//
//  SXBaseSheetView.swift
//  SXBaseAlertSheetVC
//
//  Created by mac on 2019/2/14.
//  Copyright © 2019 mac. All rights reserved.
//
import UIKit

/// 从屏幕中央弹出的视图，类似系统的sheet
class SXBaseSheetView: UIView {
    // MARK: - 子类需要实现的方法
    /// 展现时的宽度
    func showWidth() -> CGFloat {
        return UIScreen.main.bounds.width
    }
    /// 展现时的高度
    public func showHeight() -> CGFloat {
        return UIScreen.main.bounds.height - 200
    }
    private class func currentWindow() -> UIWindow? {
        if let kw = UIApplication.shared.delegate?.window {
            return kw
        }
        if #available(iOS 13.0, *) {
            if let keyWindow = UIApplication.shared.connectedScenes
                    .filter({$0.activationState == .foregroundActive})
                    .map({$0 as? UIWindowScene})
                    .compactMap({$0})
                    .first?.windows
                .filter({$0.isKeyWindow}).first {
                return keyWindow
            }
            return UIApplication.shared.windows.last
        }
        return UIApplication.shared.keyWindow
    }
    class func hideAll() {
        Self.currentWindow()?.subviews.filter({$0 is Self}).forEach({$0.removeFromSuperview()})
    }
    private class func removeAllDuplicateBg() {
        Self.currentWindow()?.subviews.filter{$0.tag == 2942}.forEach{$0.removeFromSuperview()}
    }
    // MARK: - 父类提供的展示方法
    /// 显示
    public func show() {
        Self.hideAll()
        guard let  keyWin = Self.currentWindow() else {
            return
        }
        Self.removeAllDuplicateBg()
        if let _ = m_bgControl.superview {} else {
            keyWin.addSubview(m_bgControl)
        }
        keyWin.addSubview(self)
        setAllViewAlpha(alpha: 0)
        let screenH = UIScreen.main.bounds.height
        let screenW = UIScreen.main.bounds.width
        let x = (screenW - showWidth()) * 0.5
        let y = needBottomNoMargin ? screenH : screenH + 10
        frame = CGRect(x: x, y: y, width: showWidth(), height: showHeight())
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .layoutSubviews, animations: {
            self.setAllViewAlpha(alpha: 1)
            let showY = (self.needBottomNoMargin ? (screenH - self.showHeight()) : (screenH - self.showHeight()))
            self.frame = CGRect(x: x, y: showY, width: self.showWidth(), height: self.showHeight())
        }) { (finished) in
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        registKeyboardNotification()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI() {
        
    }
    func registKeyboardNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    private var needBottomNoMargin: Bool {
        return false
    }
    private func setAllViewAlpha(alpha: CGFloat) {
        self.alpha = alpha
        for subV in subviews {
            subV.alpha = alpha
        }
        m_bgControl.alpha = alpha
    }
    /// 隐藏
    @objc func hide() {
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .layoutSubviews, animations: {
            self.setAllViewAlpha(alpha: 0)
            let screenH = UIScreen.main.bounds.height
            let screenW = UIScreen.main.bounds.width
            let x = (screenW - self.showWidth()) * 0.5
            let y: CGFloat = (self.needBottomNoMargin ? screenH : (screenH - 10))
            self.frame = CGRect(x: x, y: y, width: self.showWidth(), height: self.showHeight())
        }) { (finished) in
            if finished {
                Self.removeAllDuplicateBg()
                if self.m_bgControl.superview != nil {
                    self.m_bgControl.removeFromSuperview()
                }
                self.removeFromSuperview()
//                for subV in self.subviews {
//                    subV.isHidden = true
//                }
            }
        }
    }
    private var m_firstResponder: UIView?
    /// 背景蒙板
    private let m_bgControl: UIControl = {
        let control = UIControl(frame: UIScreen.main.bounds)
        control.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        control.addTarget(self, action: #selector(hide), for: .touchUpInside)
        control.tag = 2942
        return control
    }()
}
extension SXBaseSheetView {
    @objc func keyboardWillShow(_ notification: Notification) {
        guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }
        
//        let rawFrame = value.cgRectValue
//        let keyboardFrame = view.convert(rawFrame, from: nil)
//        let keyboardheight = keyboardFrame.size.height
//
//        UIView.animate(withDuration: 0.3) { [weak self] in
//            self?.view.layoutIfNeeded()
//        }
    }
    
    @objc func keyboardWillHide(_ notification: Notification) {
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let sf = self else {
                return
            }
            let offsetY: CGFloat = UIScreen.main.bounds.height - sf.showHeight()
            let x: CGFloat = (UIScreen.main.bounds.width - sf.showWidth())*0.5
            sf.frame = CGRect(x:x, y: offsetY, width: sf.showWidth(), height: sf.showHeight())
        }
    }
}
